//企业综合信用echarts highcharts
var financialAnalysis = function (data) {
    var finance = data["finance"],
        financeRate = data["financeRate"],
        customs = data["customs"];
    var financialText = [
        "一、营业收入", "减：营业成本", "营业税金及附加", "营业费用", "管理费用", "财务费用", "资产减值损失", "加：公允价值变动收益", "投资收益", "二、营业利润",
        "加：营业外收入", "减：营业外支出", "三、利润总额", "减：应纳税所得额", "四、净利润", "资产总额"];
    var rateText = [
        "毛利率（%）", "营业利润率（%）", "净利润率（%）", "资产回报率（%）", "营业收入增长率（%）", "营业利润增长率（%）", " 净利润增长率（%）"
    ];
    var customText = [
        "进口", "出口"
    ];
    //----------------------财务图
    var finYear = [], finVal1 = [], finVal2 = [], finVal3 = [], finVal4 = [], finVal5 = [], finVal6 = [], finVal7 = [], finVal8 = [], finVal9 = [], finVal10 = [],
        finVal11 = [], finVal12 = [], finVal13 = [], finVal14 = [], finVal15 = [], finVal16 = [],
        finSRate1 = [], finSRate2 = [], finSRate3 = [], finSRate4 = [], finSRate5 = [], finSRate6 = [], finSRate7 = [], finSRate8 = [], finSRate9 = [], finSRate10 = [],
        finSRate11 = [], finSRate12 = [], finSRate13 = [], finSRate14 = [], finSRate15 = [], finSRate16 = [];
    for (var j in finance) {
        finYear.unshift(j);
        var dl = finance[j];
        var v1 = dl["revenue"], //营业收入
            v2 = dl["sales_cost"], //营业成本
            v3 = dl["sales_tax"], //营业税金及附加信息/核定征收企业经费支出
            v4 = dl["sales_expense"], //营业费用/核定征收企业换算收入总额
            v5 = dl["G_expense"], //管理费用
            v6 = dl["finance_expense"], //财务费用
            v7 = dl["asset_devaluation_losses"], //资产减值损失
            v8 = dl["fair_value_change"], //公允价值变动收益
            v9 = dl["investment_income"],//投资收益
            v10 = dl["operation_profit"], //营业利润
            v11 = dl["non_operating_income"], //营业外收入
            v12 = dl["non_operating_expense"], //营业外支出
            v13 = dl["total_profit"], //利润（亏损）总额
            v14 = dl["incometax_actual"], //实际应纳税所得额
            v15 = v13 - v14,    //净利润
            v16 = dl["assets_re"];//资产总额（矫正后）
        finVal1.unshift(v1);
        finVal2.unshift(v2);
        finVal3.unshift(v3);
        finVal4.unshift(v4);
        finVal5.unshift(v5);
        finVal6.unshift(v6);
        finVal7.unshift(v7);
        finVal8.unshift(v8);
        finVal9.unshift(v9);
        finVal10.unshift(v10);
        finVal11.unshift(v11);
        finVal12.unshift(v12);
        finVal13.unshift(v13);
        finVal14.unshift(v14);
        finVal15.unshift(v15);
        finVal16.unshift(v16);
        //------------
        if (v1 >= 0) {
            var deno = v1;
            finSRate1.unshift(toFixNum(v1 / deno));
            finSRate2.unshift(toFixNum(v2 / deno));
            finSRate3.unshift(toFixNum(v3 / deno));
            finSRate4.unshift(toFixNum(v4 / deno));
            finSRate5.unshift(toFixNum(v5 / deno));
            finSRate6.unshift(toFixNum(v6 / deno));
            finSRate7.unshift(toFixNum(v7 / deno));
            finSRate8.unshift(toFixNum(v8 / deno));
            finSRate9.unshift(toFixNum(v9 / deno));
            finSRate10.unshift(toFixNum(v10 / deno));
            finSRate11.unshift(toFixNum(v11 / deno));
            finSRate12.unshift(toFixNum(v12 / deno));
            finSRate13.unshift(toFixNum(v13 / deno));
            finSRate14.unshift(toFixNum(v14 / deno));
            finSRate15.unshift(toFixNum(v15 / deno));
            finSRate16.unshift(toFixNum(v16 / deno));
        } else {
            $("#c_financial").hide();
        }
    }
    //财务图
    $('#c_financial').highcharts({
        chart: {
            type: 'column'
        },
        colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],
        title: {
            text: '利润表垂直分析图'
        },
        xAxis: {
            categories: finYear
        },
        yAxis: {
            allowDecimals: false,
            min: 0,
            title: {
                text: '百分比（%）'
            }
        },
        tooltip: {
            formatter: function () {
                return '<b>' + this.x + '</b><br/>' +
                    this.series.name + ': ' + this.y + "%";
            }
        },
        plotOptions: {
            column: {
                stacking: 'normal'
            }
        },
        series: [{
            name: '营业成本',
            data: finSRate2,
            stack: 'sub'
        }, {
            name: '营业税金及附加',
            data: finSRate3,
            stack: 'sub'
        }, {
            name: '营业费用',
            data: finSRate4,
            stack: 'sub'
        }, {
            name: '管理费用',
            data: finSRate5,
            stack: 'sub'
        }, {
            name: '财务费用',
            data: finSRate6,
            stack: 'sub'
        }, {
            name: '资产减值损失',
            data: finSRate7,
            stack: 'sub'
        }, {
            name: '公允价值变动收益',
            data: finSRate8,
            stack: 'add'
        }, {
            name: '投资收益',
            data: finSRate9,
            stack: 'add'
        }, {
            name: '营业外收入',
            data: finSRate11,
            stack: 'add'
        }, {
            name: '营业外支出',
            data: finSRate12,
            stack: 'sub'
        }, {
            name: '所得税费用',
            data: finSRate14,
            stack: 'sub'
        }, {
            name: '营业收入',
            data: finSRate1,
            color: 'rgba(0, 0, 0,.1)',
            stack: 'add'
        }]
    });
//财务面积图
    $('#c_financial_area').highcharts({
        chart: {
            type: 'area'
        },
        title: {
            text: '财务数据趋势分析图'
        },
        xAxis: {
            categories: finYear
        },
        yAxis: {
            title: {
                text: '万元'
            },
            labels: {
                formatter: function () {
                    return this.value / 10000;
                }
            }
        },
        tooltip: {
            shared: true,
            useHTML: true,
            headerFormat: '<small>{point.key}' + '</small><table>'
        },
        plotOptions: {
            area: {
                stacking: 'normal',
                lineColor: '#666666',
                lineWidth: 1,
                marker: {
                    lineWidth: 1,
                    lineColor: '#666666'
                }
            }
        },
        series: [{
            name: '营业收入',
            data: finVal1
        }, {
            name: '营业成本',
            data: finVal2
        }, {
            name: '营业税金及附加',
            data: finVal3
        }, {
            name: '营业费用',
            data: finVal4
        }, {
            name: '管理费用',
            data: finVal5
        }, {
            name: '财务费用',
            data: finVal6
        }, {
            name: '资产减值损失',
            data: finVal7
        }, {
            name: '公允价值变动收益',
            data: finVal8
        }, {
            name: '投资收益',
            data: finVal9
        }, {
            name: '营业利润',
            data: finVal10
        }, {
            name: '营业外收入',
            data: finVal11
        }, {
            name: '营业外支出',
            data: finVal12
        }, {
            name: '利润总额',
            data: finVal13
        }, {
            name: '应纳税所得额',
            data: finVal14
        }, {
            name: '净利润',
            data: finVal15
        }, {
            name: '资产总额',
            data: finVal16
        }]
    });
    var c_finOpt = $('#c_financial_area').highcharts().series;
    createBsTable("c_financial_table", c_finOpt, financialText, finYear, "名称/年份");
    var $finlatr = $("#c_financial_table tbody tr:last-child");
    $finlatr.before("<tr class='dividertr'><td></td></tr>");
//--------------------各种比率图
    var finRateYear = [], finRVal1 = [], finRVal2 = [], finRVal3 = [], finRVal4 = [], finRVal5 = [], finRVal6 = [], finRVal7 = [];
    for (var i in financeRate) {
        finRateYear.unshift(i);
        var dd = financeRate[i];
        finRVal1.unshift(toFixNum(dd["gross"]));//毛利率（%）
        finRVal2.unshift(toFixNum(dd["profit"]));//营业利润率（%）
        finRVal3.unshift(toFixNum(dd["profit_net"]));//净利润率（%）
        finRVal4.unshift(toFixNum(dd["asset_return"]));//资产回报率（%）
        finRVal5.unshift(toFixNum(dd["income_increase"]));//营业收入增长率（%）
        finRVal6.unshift(toFixNum(dd["profit_increase"]));//营业利润增长率（%）
        finRVal7.unshift(toFixNum(dd["profit_net_increase"]));//净利润增长率（%）
    }
    function toFixNum(num) {
        if (num == "") {
            return num;
        } else {
            if (Math.abs(num) < 0.005) {
                return parseFloat((num * 100).toFixed(3));
            } else {
                return parseFloat((num * 100).toFixed(2));
            }
        }
    }

//财务指标
    $('#c_financial_rate').highcharts({
        title: {
            text: '财务指标趋势分析图',
            x: -20
        },
        xAxis: {
            categories: finRateYear
        },
        yAxis: {
            title: {
                text: '百分数 (%)'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: '%'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: [{
            name: '毛利率（%）',
            data: finRVal1
        }, {
            name: '营业利润率（%）',
            data: finRVal2
        }, {
            name: '净利润率（%）',
            data: finRVal3
        }, {
            name: '资产回报率（%）',
            data: finRVal4
        }, {
            name: '营业收入增长率（%）',
            data: finRVal5
        }, {
            name: '营业利润增长率（%）',
            data: finRVal6
        }, {
            name: '净利润增长率（%）',
            data: finRVal7
        }]
    });
    var c_finROpt = $('#c_financial_rate').highcharts().series;
    createBsTable("c_rate_table", c_finROpt, rateText, finYear, "财务比率/年份");
//----------------------进出口
    if (customs == "") {
        $(".c_importers").hide();
    } else {
        var imports = customs[1], exports = customs[2], customsYear = [], cuExVal = [], cusImVal = [], cusImdata = [], cusExdata = [];
        var now = 2016;
        var getseriesdata = function (obj, id) {
            for (var o in obj) {
                var cu_year = now.toString().substr(0, 2) + o.substr(0, 2),
                    cu_mon = o.substr(2),
                    str = cu_year + "-" + cu_mon,//e.g.:2015-12
                    strtimr = Date.parse(str),
                    val = parseFloat(obj[o]),
                    midarr = [];
                if (!val) {
                    val = "";
                }
                midarr.push(strtimr);
                midarr.push(val);
                if (id == "exports") {
                    customsYear.push(str);
                    cuExVal.push(val);
                    cusExdata.push(midarr);
                } else {
                    cusImVal.push(val);
                    cusImdata.push(midarr);
                }
                midarr = [];
            }
        };
        getseriesdata(imports, "imports");
        getseriesdata(exports, "exports");
        //进出口
        $('#c_importers').highcharts({
            chart: {
                alignTicks: false
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            xAxis: [{
                categories: customsYear
            }],
            yAxis: [{
                title: {
                    text: ''
                }
            }],
            series: [{
                name: '进口',
                type: 'column',
                pointStart: 0,
                data: cusImVal
            }, {
                name: '出口',
                type: 'column',
                pointStart: 0,
                data: cuExVal
            }, {
                name: '进口',
                type: 'spline',
                pointStart: 0,
                marker: {
                    enabled: false
                },
                data: cusImVal
            }, {
                name: '出口',
                type: 'spline',
                pointStart: 0,
                marker: {
                    enabled: false
                },
                data: cuExVal
            }]
        });
        var endYear = customsYear[0].substr(0, 4);//小的
        var startYear = customsYear[customsYear.length - 1].substr(0, 4);//最近的年份
        //海关按年份拆分多个表格
        for (var nyear = startYear; nyear >= endYear; nyear--) {
            var arrYear = [];
            var opt1 = [], opt2 = [], opt = [];
            for (var cc in customsYear) {
                var _this = customsYear[cc];
                var imdata = cusImdata[cc];
                var exdata = cusExdata[cc];
                if (_this.indexOf(nyear) > -1) {
                    arrYear.push(_this);
                    opt1.push(imdata[1]);
                    opt2.push(exdata[1]);
                }
            }
            opt.push(opt1, opt2);
            createBsTable("c_importers_table" + nyear, opt, customText, arrYear, "名称/时间");
            arrYear = [];
            opt1 = [];
            opt2 = [];
            opt = [];
        }
    }
    function createBsTable(id, opt, text, year, head) {
        var customnum = id.indexOf("c_importers_table");
        if (customnum > -1) {
            var table = $("#c_importers_table");
            var yeard = id.substr(id.length - 4);
            var _thistable = $("<table class='pdf-table'  id='" + id + "'><caption><span>" + yeard + " 年</span></caption><thead></thead><tbody></tbody></table>");
            table.append(_thistable);
        }
        var tables_thead = $("#" + id).find("thead");
        var tables_tbody = $("#" + id).find("tbody");
        var trs = $("<tr></tr>"),
            tabth, tabtr;
        //th标题
        for (var i = 0, len = year.length; i < len; i++) {
            var td1 = $("<th></th>").append(year[i]);
            tabth = trs.append(td1);
        }
        var fText = $("<th class='table_th'></th>").append(head);
        tabth.prepend(fText);
        tables_thead.append(tabth);
        //tr每一行内容
        for (var l = 0, lenl = text.length; l < lenl; l++) {
            var td3 = $("<td></td>").append(text[l]);
            trs = $("<tr></tr>").append(td3);
            if (customnum < 0) {
                var onetd = opt[l].yData;
            } else {
                onetd = opt[l];
            }
            for (var m = 0, lenm = onetd.length; m < lenm; m++) {
                var num = onetd[m];
                if (num) {
                    num = num.toLocaleString("en-US");
                }
                var td2 = $("<td></td>").append(num);
                tabtr = trs.append(td2);
            }

            trs = $("<tr></tr>");
            tables_tbody.append(tabtr);
        }
    }
};
//海关进出口商品详情
var imdetailtab = function (datas) {
    var detailtable = $("#c_importers_detail_table tbody");
    for (var key in datas) {
        var val = datas[key];
        var len = Object.keys(val).length;
        for (var k in val) {
            var val2 = val[k];
            var tr = $("<tr><td class='table_td detail_year'>" + key + "</td><td>" + k + "</td><td>" + val2[0] + "</td><td>" + val2[1] + "</td></tr>");
            detailtable.append(tr);
        }
        var years = $("#c_importers_detail_table .detail_year");
        years.each(function (index) {
            if (index == 0) {
                $(this).attr("rowspan", len).removeClass("detail_year table_td").addClass("table_year");
            } else {
                $(this).remove();
            }
        })
    }
    $(".table_year").parent(".table_tr").prev(".table_tr").addClass("tr_border");
};